<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;

class CustomerRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $user = Auth::User();
        $customerId = $this->route('customer');
        if (!empty($customerId)) {
            if (!$user->can('update', new Customer())) {
                abort(403, 'This action is unauthorized.');
            }
        } else {
            if (!$user->can('store', new Customer())) {
                abort(403, 'This action is unauthorized.');
            }
        }
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $customerId = $this->route('customer');
        if (!empty($customerId)) {
            return [
//                'baseInfo.name' => 'required',
                'baseInfo.mobile' => 'unique:customers,baseInfo.mobile,'.$customerId.',_id|regex:/^1[0-9]{10}$/',
            ];
        } else {
            return [
                'customer.baseInfo.name' => 'required',
                'customer.baseInfo.mobile' => 'regex:/^1[0-9]{10}$/',
            ];
        }
    }

    public function messages()
    {
        return [
            'baseInfo.mobile.unique' => ':attribute已存在',
        ];
    }

    public function attributes()
    {
        return [
            'customer.baseInfo.name'    => '客户姓名',
            'customer.baseInfo.mobile'  => '客户手机号',
            'baseInfo.name'             => '姓名',
            'baseInfo.mobile'           => '手机号',
        ];
    }
}
